<template>
  <div class='settlement'>
    <van-cell-group class="cards" :border="false" inset @click="jump">
      <van-cell class="address" :title="concatAddress" :border="false" is-link center>
        <template #label>
          <span>{{address.name}}</span>
          <span class="tel">{{address.phone}}</span>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group class="cards" :border="false" inset>
      <div v-for="(item, index) in list" :key="index">
        <van-cell class="shopurl" :title="item.shop_name" :icon="`${resourceURL}${item.imagesurl}`" :border="false" center />
        <van-card class="product" v-for="(items, indexs) in item.product" :key="indexs" :num="items.quantity" :price="item.mprice" :desc="items.p_s_name" :title="items.product_name" :thumb="`${resourceURL}${items.imageurl}`" />
      </div>
    </van-cell-group>

    <van-cell-group class="cards" :border="false" inset>
      <van-cell title="配送服务" :value="`快递￥${price.express_fee}`" :border="false" center />
    </van-cell-group>

    <van-cell-group class="cards" :border="false" inset>
      <van-cell title="0明细" class="price_detail" :border="false" center />
      <van-cell class="price_total" :value="`￥${price.products_amount}`" :border="false" center>
        <template #title>
          <span>商品总价</span>
          <span class="num_total">共{{totalProductLength}}件商品</span>
        </template>
      </van-cell>
      <van-cell class="coupon" title="消费券" :icon="require('@/assets/img/coupon.png')" :border="false" is-link center @click="showActionSheet">
        <template #default>
          <span v-if="!coupon_amount" class="not_coupon">无消费券</span>
          <span v-else class="is_coupon">-￥{{coupon_amount}}</span>
        </template>
      </van-cell>
      <van-cell class="price_total" title="合计" :value="`￥${price.pay_amount}`" :border="false" center />
    </van-cell-group>

    <div class="submit">
      <div class="price_info">
        <div class="settlement_total">
          <span class="num_total">共{{totalProductLength}}件商品</span>
          <span class="pay_amount">合计:￥<span>{{price.pay_amount}}</span></span>
        </div>
        <div v-if="coupon_amount" class="coupon_amount">共减￥{{coupon_amount}}</div>
      </div>
      <van-button type="primary" round @click="onPayment">去支付</van-button>
    </div>
    <!-- 选择消费券 -->
    <van-action-sheet class="action_sheet" v-model="showCoupon" title="请选择消费券" :style="{height:'80%'}">
      <div class="content">
        <van-loading v-if="loading" class="loading_wait" color="#B60102" />
        <van-list v-else v-model="loading" :finished="finished" finished-text="没有更多了" @load="usercouponlist" :error.sync="err" error-text="加载失败，点击这里重试">
          <van-radio-group v-model="coupon_id">
            <div class="item" v-for="(item, index) in couponList" :key="index" @click="toggle(item,index)">
              <div class="left">
                <div class="discount" :class="zoomFont(item.discount)"><span>￥</span>{{parseInt(item.discount)}}</div>
                <div class="fullmoney">满{{ parseInt(item.fullmoney) }}元可用</div>
              </div>
              <div class="right">
                <div class="text">
                  <div class="name">{{ item.coupon_name }}</div>
                  <div class="time">{{ item.start }}-{{ item.end }}</div>
                </div>
                <div class="btn">
                  <van-radio :ref="`checkboxes${index}`" :name="item.receive_id" />
                </div>
              </div>
            </div>
          </van-radio-group>
        </van-list>
      </div>
    </van-action-sheet>
  </div>
</template>
<script src="http://wechatfe.github.io/vconsole/lib/vconsole.min.js?v=3.2.0"></script>
<script>
import { Toast } from 'vant';
export default {

  data () {
    return {
      receive_id: null,
      address: {},
      list: [],
      price: {},
      err: false,
      showCoupon: false,
      loading: false,
      finished: false,
      couponList: [],
      coupon_id: 0,
      coupon_amount: null,
      limit: 50,
      oid: ""
    }
  },
  created () {
    if (this.$route.query.item) {
      this.address = JSON.parse(this.$route.query.item)

    } else {
      this.getDefaultaddress()
    }
    this.getSettlement()
  },
  computed: {

    // 拼接完整地址
    concatAddress () {
      if (this.address.province_name) {

        return this.address?.province_name + this.address?.city_name + this.address?.area_name + this.address?.detail
      } else {
        return ''
      }
    },
    // 统计商品数量
    totalProductLength () {
      let sum = 0;
      for (let index = 0; index < this.list.length; index++) {
        let num = this.list[index].product.length
        sum += num
      }
      return sum
    },
    // 缩放文字
    zoomFont () {
      return ((e) => {
        return e > 99 ? 'zoom1' : e > 999 ? 'zoom2' : ''
      })
    },
  },
  methods: {
    // 打开选择消费券弹窗
    showActionSheet () {
      this.couponList = []
      this.showCoupon = true
      this.usercouponlist()
    },
    // 下单
    onPayment () {
      if (this.address) {

        this.$axios.post(this.$api.GoToPlace, {
          cart_ids: this.$store.state.cart_id,
          receive_id: this.coupon_id,
          address_id: this.address.address_id,
        }).then(res => {
          if (res.data.code == 1) {
            console.log(res.data.data);
            //this.Payment(res.data.data.orders[0])
            this.StartWeiXinPay(res.data.data)
            this.oid = res.data.data.data.order_id
          } else {
            Toast.fail(res.data.msg)
          }
        })
      } else {
        Toast.fail('暂无收货地址')
      }
    },

    // Payment (id) {
    //   this.$axios.post(this.$api.tobepaid, {
    //     order_id: id,
    //   }).then(res => {

    //     if (res.data.code == 1) {
    //       this.StartWeiXinPay(res.data.data.data)
    //     } else {
    //       Toast.fail(res.data.msg)
    //     }
    //   })
    // },
    // 调取微信支付
    StartWeiXinPay (pay_params) {
      if (typeof window.WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(pay_params), false)
          alert(1);
        } else if (document.attachEvent) {
          alert(2);
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(pay_params))
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(pay_params))
        }
      } else {
        this.onBridgeReady(pay_params)
      }
    },
    onBridgeReady (pay_params) {
      var that = this
      window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
        'appId': pay_params.appId, // 公众号名称，由商户传入
        'timeStamp': pay_params.timeStamp, // 时间戳，自1970年以来的秒数
        'nonceStr': pay_params.nonceStr, // 随机串
        'package': pay_params.package, //统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
        'signType': pay_params.signType, // 微信签名方式：
        'paySign': pay_params.paySign // 微信签名
      },
        function (res) {

          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            setTimeout(() => {
              that.$router.replace({ name: 'paymentSucess', query: { order_id: that.oid } })
            }, 500);
          } else {
            Toast.fail('支付失败')
            this.$store.commit('setOrderTab', 1);
            setTimeout(() => {
              that.$router.replace({ name: 'order' })
            }, 500);
          }
        }
      )
    },
    // 获取消费券列表
    usercouponlist () {
      this.loading = true
      this.$axios.get(this.$api.usercouponlist, {
        params: {
          page: this.page,
        },
      }).then((res) => {
        if (res.data.code == 1) {
          let result = res.data.data.data.map(e => {
            return {
              ...e,
              start: this.$moment(Number(e.use_stime) * 1000).format('YYYY年MM月DD日'),
              end: this.$moment(Number(e.use_etime) * 1000).format('YYYY年MM月DD日'),
            }
          })
          this.couponList.push(...result)
          this.loading = false
          if (result.length < this.limit) {
            this.finished = true // 大于所有条数则结束加载
          }
          if (result.length > this.limit) this.page++
        } else {
          // 加载失败时
          this.err = true
          this.finished = true
          this.loading = false
        }
      });
    },
    // 用事件代理选择消费券
    toggle (item, index) {
      this.$refs[`checkboxes${index}`][0].toggle();
      this.coupon_amount = item.discount
      this.$axios.post(this.$api.settlement, {
        cart_ids: this.$store.state.cart_id,
        receive_id: item.receive_id,
      }).then(res => {
        this.list = res.data.data.list
        this.price = res.data.data.price
        if (res.data.data.is_coupon) {
          this.showCoupon = false
        } else {
          this.coupon_id = null
          this.coupon_amount = null
          Toast.fail({ message: '消费价格未达标，无法使用该消费券', duration: 3000 })
        }
      })
    },
    // 获取收货地址
    getDefaultaddress () {
      this.$axios.get(this.$api.getdefaultaddress).then(res => {

        if (this.$route.query.item) {
          Toast.clear();
        } else {
          this.address = res.data.data
        }


      })
    },
    // 获取结算页内容
    getSettlement () {
      this.$axios.post(this.$api.settlement, {
        cart_ids: this.$store.state.cart_id,
        receive_id: this.receive_id,
      }).then(res => {
        this.list = res.data.data.list
        this.price = res.data.data.price
      })
    },

    //跳转至选择地址页
    jump () {
      this.$router.push({
        name: 'chooseAddress',
        query: {
          name: 'settlement'
        }
      })
    }
  },
}
</script>

<style scoped lang='less'>
.settlement {
  padding-top: 16px;
  .cards {
    margin-bottom: 12px;
    /deep/.van-icon__image {
      width: 100%;
      height: 100%;
    }
    .address {
      /deep/.van-cell__title {
        font-size: 14px;
        font-weight: bold;
      }
      /deep/.van-cell__label {
        font-size: 14px;
        font-weight: 500;
      }
    }
    .shopurl {
      .van-cell__left-icon {
        display: flex;
        align-items: center;
        width: 20px;
        height: 22px;
        margin-right: 8px;
      }
    }
    .product {
      margin-top: 0;
      background-color: #fff;
      /deep/.van-card__title {
        font-size: 14px;
      }
      /deep/ .van-card__price {
        font-size: 14px;
      }
    }
    .price_detail {
      font-weight: bold;
    }
    .coupon {
      .van-cell__left-icon {
        display: flex;
        align-items: center;
        width: 22px;
        height: 22px;
        margin-right: 8px;
      }
      .not_coupon {
        font-size: 12px;
        color: #bbb9b7;
      }
      .is_coupon {
        font-size: 12px;
        color: #fb2b2c;
      }
    }
  }
  .tel {
    margin-left: 16px;
  }
  .price_total {
    /deep/.van-cell__value {
      color: #06021a;
      font-size: 14px;
      font-weight: bold;
    }
  }
  .submit {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    padding: 5px 16px;
    border-radius: 16px 16px 0 0;
    background-color: #fff;
    box-sizing: border-box;
    .price_info {
      display: flex;
      flex-flow: column wrap;
      align-items: flex-end;
      margin-right: 16px;
      .settlement_total {
        font-size: 12px;
        .pay_amount span {
          color: #fb2b2c;
          font-size: 18px;
          font-weight: bold;
        }
      }
      .coupon_amount {
        color: #fb2b2c;
        font-size: 12px;
      }
    }
    .van-button {
      min-width: 102px;
    }
  }
  .num_total {
    color: #bbb9b7;
    font-size: 12px;
    margin-left: 14px;
    margin-right: 8px;
  }
  .action_sheet {
    .content {
      padding: 16px 16px;
      box-sizing: border-box;
      .loading_wait {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 200px;
      }
      .item {
        display: flex;
        border: 1px solid #d56869;
        padding: 12px;
        margin-bottom: 12px;
        border-radius: 10px;
        box-sizing: border-box;
        .left {
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          align-items: center;
          width: 100px;
          min-height: 75px;
          border-right: 1px dashed #f9a254;
          .discount {
            font-size: 38px;
            color: #d56869;
            span {
              font-size: 20px;
            }
          }
          .zoom1 {
            transform: scale(0.8);
          }
          .zoom2 {
            transform: scale(0.6);
          }
          .fullmoney {
            font-size: 12px;
            font-weight: 400;
            color: #d56869;
          }
        }
        .right {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          min-height: 75px;
          padding-left: 14px;
          .name {
            max-width: 173px;
            color: #470607;
            font-size: 16px;
            font-weight: bold;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
          }
          .time {
            color: #606060;
            font-size: 10px;
            font-weight: 400;
            margin-top: 4px;
          }
          .btn {
            display: flex;
            justify-content: flex-end;
          }
        }
      }
    }
  }
}
</style>
